# -*- coding: UTF-8 -*-

from __future__ import absolute_import, division, print_function, unicode_literals

import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])

# Import the backtrader platform
import backtrader as bt

import MySQLDataFeed as mdf
import SimpleMySqlClass as smc
import talib as talib
import numpy as np
import akshare as ak
import pandas as pd
import json

# 1，输入code
# 2，检查沪深300，中正500是否在内
# 3，检查 t_stock_data_daily_${code} 是否建表，创建表
# 4，拉取code日线数据，落库
# 5，跑双均线模型回测
# 6，记录开仓买卖记录到流水表


def log(out_put):
    print("%s", out_put)


def backtrader_test_by_data(code, name, isShowPlot):
    # Create a cerebro entity
    cerebro = bt.Cerebro()
    cerebro.addstrategy(MarketTrendStrategy)

    tableName = "t_trade_data_" + code
    sql = f"select `date`, `open`, `high`, `low`, `close`, `volume` from {tableName} where date>'2022-01-01' limit 3000"

    data = mdf.MySQLDataFeed(sql)
    print("data = ", data)
    # Add the Data Feed to Cerebro
    cerebro.adddata(data, name=name)

    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.FixedSize, stake=100)

    results = cerebro.run()

    results = cerebro.plot(style="candle", barup="red", bardown="green", volume=True)


class MarketTrendStrategy(bt.Strategy):
    params = (
        ("short_window", 50),
        ("long_window", 200),
        ("volatility_threshold", 0.01),
    )

    def __init__(self):
        self.short_ma = bt.indicators.SimpleMovingAverage(
            self.data.close, period=self.p.short_window
        )
        self.long_ma = bt.indicators.SimpleMovingAverage(
            self.data.close, period=self.p.long_window
        )
        self.volatility = bt.indicators.StandardDeviation(self.data.close, period=20)

    def next(self):
        if (
            self.short_ma[0] > self.long_ma[0]
            and self.volatility[0] < self.p.volatility_threshold
        ):
            print(f"----------->>>>>>{self.data.datetime.date(0)} 处于牛市阶段")
        elif (
            self.short_ma[0] < self.long_ma[0]
            and self.volatility[0] < self.p.volatility_threshold
        ):
            print(f"{self.data.datetime.date(0)} 处于熊市阶段<<<<<----------")
        else:
            print(f"{self.data.datetime.date(0)} 处于震荡市阶段")


if __name__ == "__main__":
    # '600519', '贵州茅台'
    # 300438	鹏辉能源
    # 伊利股份[600887]
    # code = "000333"
    # name = "美的集团"
    # code = "600887"
    # name = "伊利股份"
    code = "510300"
    name = "沪深300ETF"
    # conn = get_mysql_conn()
    # # # code = "002594"
    # get_data_and_read(conn, code)
    backtrader_test_by_data(code, name, True)
    # conn.close()
    # test_back_trade()

    # conn = get_mysql_conn()
    # get_fund_stock_to_db(conn)
    # conn.close()
